// pages/confirm_order/confirm_order.js
let feedbackApi= require('../common/showToast.js');
const getToken= require('../../utils/get_token.js');
let pood, memberId,openId = '',poodId = '',hebiRedFlag;
let cookie, token;
const ckToken = async (that) => {//token确认
  let nTime = Math.floor(new Date().getTime() / 1000);
  let oldTime = wx.getStorageSync('ntime') || 0;
  if (nTime < oldTime)//现在的时间小于到期时间
  {
    thou(that);
  } else {
    await getToken.getToken();
    thou(that);
  }
}
const thou = (that) => {//token没有失效时执行的代码
  defaltAdd(that);
  if (openId == '') {
    getToken.getOpenId(function (res) {
      wx.setStorageSync('openId', res.data.openId);
      openId = res.data.openId;
    });
  }
}
const defaltAdd = function (that) {
  let params = [ 'common/receiver/list',{"id": memberId}]
  getToken.getData(function (res) {
    console.log(res)
    let sure = true;
    let listA = res.data.lists;
    let lists = '';
   if(pood.zt){
    that.data.typeA = 3;
    if(listA.length > 0){
      that.setData({ 
        shipName: listA[0].name,
        shipMobile: Number(listA[0].mobile)
      })
    }
    that.data.ntShow=false;
   }else{
    if (listA.length <= 0) {//没有地址列表
      that.data.typeA = 1;
    } else {//有默认地址
      that.data.typeA = 2;
      for (let i = 0; i < listA.length; i++) {
        if (listA[i].isdefault) {
          lists = listA[i];
          sure = false;
        }
      }
      if (sure)//无默认地址
      {
        lists = listA[0]
      }
      that.data.addId = lists.id;
      if (!that.data.isNaSales)//有地区限制
      {
        checkArea(that);
      } else {
        that.data.ntShow=false
      }
      that.setData({
        name: lists.name,
        phone: lists.mobile,
        address: lists.address,
        addId: that.data.addId
      })
    }
   }
  that.setData({typeA: that.data.typeA,ntShow:that.data.ntShow})
  }, ...params)
};

const checkArea = (that) => {//验证地址
  let params = [ 'shop/pingTuan/isSupportSales', {"goodsId":that.data.goodsId,"id": that.data.addId}]
  getToken.getData(function (res) {
    console.log(res.data);
    if (res.data.flag && !res.data.isSupportSales) {
      that.data.ntShow=true;
    } else {
      that.data.ntShow=false;
    }
  }, ...params)
}
const getTuanId = (that) => {
  let params = ['shop/pingTuan/shareTuanId', {"membId":memberId,"setId":pood.id}]
  getToken.getData(function (res) {
    console.log(res.data);
    wx.reLaunch({
      url: '/pages/tsucc/tsucc?id=' + poodId + '&tuanid=' + res.data.result.id + '&types=1&incom=' + that.data.tuanInCome
    })
  }, ...params)
}
const jia=function(that,id,limit){//数量加事件 limit是限制的值，
  that.data.pd.allNum = that.data.proList.reduce(function (prev, cur) {
     return cur.num + prev;
  }, 0); 
  if(that.data.pd.allNum<limit){//当前总数小于限制数
    for(let i=0;i<that.data.proList.length;i++){
      if(id==that.data.proList[i].id){
         that.data.proList[i].num+=1;
         that.data.pd.allNum+=1;
      }
    }
    that.data.pd.allMoney = that.data.proList.reduce(function (prev, cur) {
      let oMoney=(cur.intPinPrice/100)*cur.num;
      return oMoney + prev;
    }, 0);
    if(that.data.pd.min<=that.data.pd.allNum){//如果一个人买完
      that.data.qobj.show=false;
    }
    that.data.pd.allMoney=that.data.pd.allMoney.toFixed(2);
    that.setData({pd:that.data.pd,proList:that.data.proList,qobj:that.data.qobj})
  }else{
    feedbackApi.showToast({ title: that.data.message, mask: false });
  }
}
const jian=function(that,id,limit){//数量加事件 limit是限制的最小值，
  that.data.pd.allNum = that.data.proList.reduce(function (prev, cur) {
     return cur.num + prev;
  }, 0); 
  if(limit<that.data.pd.allNum){
    for(let i=0;i<that.data.proList.length;i++){
      if(id==that.data.proList[i].id){
         if(that.data.proList[i].num>0){
          that.data.proList[i].num-=1;
          that.data.pd.allNum-=1;
         }
      }
    }
    that.data.pd.allMoney = that.data.proList.reduce(function (prev, cur) {
      let oMoney=(cur.intPinPrice/100)*cur.num;
      return oMoney + prev;
    }, 0);
    if(that.data.pd.min>that.data.pd.allNum){//如果一个人买完
      that.data.qobj.show=true;
    }
    that.data.pd.allMoney=that.data.pd.allMoney.toFixed(2);
    that.setData({pd:that.data.pd,proList:that.data.proList,qobj:that.data.qobj})
  }else{
    if(pood.classiy===0){
      feedbackApi.showToast({ title: `商品${pood.min}份起批`, mask: false });
    }
  }
}
const gets=function(that,num){
  that.data.proList[0].num=Number(num);
  that.data.pd.allMoney=that.data.proList[0].num*(that.data.proList[0].intPinPrice/100);
  that.data.pd.allMoney=that.data.pd.allMoney.toFixed(2);
  if(that.data.proList[0].num>=that.data.pd.min){
    that.data.qobj.show=false;
  }else{
    that.data.qobj.show=true;
  }
  that.setData({proList: that.data.proList,pd:that.data.pd,qobj:that.data.qobj})
}
Page({

  /**
   * 页面的初始数据
   */
	data: {
    shipName:'',
    shipMobile:'',
		name: '',
		phone: '',
		address: '',
		addId: '',
		limitA:1,
		memberId: '',
		memo: '',
    typeA:0,
		boolT:true,
		loading:false,
		disabled:false,
    ntShow:true,
    goodsId:'',
    tuanInCome:0,
    isNaSales:true,
    avatarUrl:'',
    isbest:false,
    proList:[],
    pd:{},
    qobj:{'name':'支付后需邀请用户参团','show':true},
    message:'已超过拼团份数限制',
    smList:[]
	},

  /**
   * 生命周期函数--监听页面加载
   */
	onLoad: function (options) {
		var that = this;
    poodId = options.id;
    openId = wx.getStorageSync('openId') || '';
		memberId = wx.getStorageSync('memberId');
    cookie = wx.getStorageSync('cookie') || '';
    token = wx.getStorageSync('token') || '';
    pood = wx.getStorageSync('pood');
    hebiRedFlag= wx.getStorageSync('hebiRedFlag') || '';
    console.log(pood)
    if(pood.zt){//自提商品
      if(pood.classiy==1){//开团
        that.data.smList=[{'id':2,'name':'批发方式','type':'拼团购买','sm':'团长开团，邀请好友参团，拼团成功，商家发货','img':'../../image/xiala.png','show':false}]
      }else{//直接购买
        that.data.smList=[{'id':2,'name':'批发方式','type':'直接购买','sm':'下单即购买成功，等待商家发货','img':'../../image/xiala.png','show':false}]
      } 
    }else{
      if(pood.classiy==1){//开团
        that.data.smList=[
          {'id':1,'name':'配送方式','type':'快递物流配送，团员自取','sm':'商品统一打包快递配送至团长收货地址，团员自取','img':'../../image/xiala.png','show':false},
          {'id':2,'name':'批发方式','type':'拼团购买','sm':'团长开团，邀请好友参团，拼团成功，商家发货','img':'../../image/xiala.png','show':false}]
      }else{//直接购买
        that.data.smList=[
          {'id':1,'name':'配送方式','type':'快递物流配送','sm':'商品统一打包，快递物流配送到家','img':'../../image/xiala.png','show':false},
          {'id':2,'name':'批发方式','type':'直接购买','sm':'下单即购买成功，等待商家发货','img':'../../image/xiala.png','show':false}]
      } 
    }
    if(pood.limit>0){//有购买限制
      that.data.limitA=pood.limit;
      that.data.message=`商品限购${pood.limit}份`;
    }else{//无限制
      if(pood.classiy==1){
        that.data.limitA=pood.max;
      }else{//单独购买
        //that.data.limitA=pood.store;
        that.data.message=`超过购买份数限制`;
        that.data.limitA=pood.max;
      }
    }
    for(let i=0;i<pood.tallList.length;i++){
      if(pood.tallList[i].num>0){
        if(pood.twogShow){
          pood.tallList[i].name=`${pood.tallList[i].speciValueStoreList[0].name}+${pood.tallList[i].speciValueStoreList[1].name}`;
        }
        that.data.proList.push(pood.tallList[i]);
      }
    }
    if(pood.isbest){
      that.data.qobj.name='支付后需邀请新用户参团';
    }
    if(pood.min<=pood.allNum){
      that.data.qobj.show=false;
    }
    that.setData({pd: pood,proList:that.data.proList,smList:that.data.smList,qobj:that.data.qobj});
    if (pood.zt) {
      that.data.addId = pood.zitiAddressList[0].id;
      that.setData({addresst: pood.zitiAddressList[0]}) 
    }
	},
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    let that = this;
    ckToken(that);
  },
  jiaB(e){//单独购买数量加事件
    let that = this;
    let id = e.currentTarget.dataset.id;
    jia(that,id,that.data.limitA);
  },
  jianB(e){//单独购买数量减事件
    let that = this;
    let id = e.currentTarget.dataset.id;
    let limit=1;
    if(that.data.pd.classiy===0){//单独购买
       limit=that.data.pd.min;
    }
    jian(that,id,limit);
  },
  nameBlur: function (e) {
    let that = this;
    e.detail.value = e.detail.value.replace(/\s/g, "");
    that.setData({
      shipName: e.detail.value
    })
  },
  phoneBlur: function (e) {
    let that = this;
    e.detail.value = e.detail.value.replace(/\s/g, "");
    that.setData({
      shipMobile: e.detail.value
    })
  },
  spend:function(e){//展示框
    let that = this;
    let id = e.currentTarget.dataset.id;
    that.data.smList.forEach(function(ele,index,arr){
        if(id==ele.id){
          ele.show=!ele.show;
          if(ele.show){
            ele.img='../../image/shouhui.png';
          }else{
            ele.img='../../image/xiala.png';
          }
        }
    })
    that.setData({
      smList:that.data.smList
    })
  },
  enterZt: function (e) {
    var that = this;
    if (that.data.boolT) {
      that.data.boolT = false;
      wx.redirectTo({
        url: '../zt/zt?page=1&id=' + poodId,
        success: function () {
          setTimeout(function () {
            that.data.boolT = true;
          }, 500)
        }
      })
    }
  },
	changeAdd: function (e) {
		let that = this;
		if (that.data.boolT) {
			that.data.boolT = false;
      wx.redirectTo({
        url: '../l_address/l_address?page=paired_order&id=' + poodId,
				success: function () {
					setTimeout(function () {
						that.data.boolT = true;
					}, 500)
				}
			})
		}	
	},
  go_newA:function(e){//添加新地址
    let that = this;
    if (that.data.boolT) {
      that.data.boolT = false;
      wx.navigateTo({
        url: '../new_address/new_address',
        success: function () {
          setTimeout(function () {
            that.data.boolT = true;
          }, 500)
        }
      })
    }	
  },
  go_sale: function (e) {//去限制地区详情
    let that = this;
    if (that.data.boolT) {
      that.data.boolT = false;
      wx.navigateTo({
        url: '../sale/sale?id=' + that.data.goodsId,
        success: function () {
          setTimeout(function () {
            that.data.boolT = true;
          }, 500)
        }
      })
    }
  },
  bindKeyInput: function (e) {//获取光标
    let that=this;
    let mNum=e.detail.value;
    let limiMin=1;
    if(mNum!==''){
     if(mNum>that.data.limitA){
        mNum=that.data.limitA
     } 
     if(mNum<limiMin){
       mNum=limiMin
     }
     gets(that,mNum);
    }
  },
  blurInput:function(e){//失去光标
    let that=this;
    let mNum=e.detail.value;
    let minNum=1;
    if(pood.classiy===0){
      minNum=pood.min;
      if(mNum=='')
      {
        gets(that,minNum);
      }else{
        if(mNum<minNum){//当前数量小于最小值
          gets(that,minNum);
        }
      }
    }
  },
	submitOrder: function (e) {//开团
    let that = this;
    if(that.data.isbest&&hebiRedFlag!=1){//新人专享，但不是新人 
      feedbackApi.showToast({ title: '新人专享商品，只有新人才能开团', mask: false });
      return false;
    }
    if (pood.zt)
    {
      if (that.data.shipName=='')
     {
        feedbackApi.showToast({ title: '请先输入姓名！', mask: false });
        return false;
     }
      if (that.data.shipMobile == '') {
        feedbackApi.showToast({ title: '请先输入联系电话！', mask: false });
        return false;
      }
    }
    if (that.data.ntShow)
    {
      feedbackApi.showToast({ title: '对不起,您所选的地区不销售此商品', mask: false });
      return false;
    }
    let gId = pood.id;//商品id
    let productId = that.data.proList[0].productId;
    let receiverId = that.data.addId;//地址id
    let busId = pood.busId;//店铺id
    let shipName = that.data.shipName;//姓名
    let shipMobile = that.data.shipMobile;//电话
    let mAmount = pood.max;
    let myAount = that.data.proList[0].num;
    
		that.setData({loading:true,disabled:true})
    let  url = 'shop/pinTuanPay/wechatPinTuanHxsmTransferNewSheQuInt';
    let para = '{"openId":"' + openId + '","productId":"' + productId + '","setId":"' + gId + '","busId":"' + busId + '","tuanMemberNum":' + mAmount + ',"buyCount":' + myAount + ',"membId":"' + memberId + '","receiverId":"' + receiverId + '","isMini":"mini","memo":"","shipName":"' + shipName + '","shipMobile":"' + shipMobile+'"}';
    let params = [ 'shop', url, para]
    getToken.pay(function (res) {
      console.log(res.data);
      if (res.data.flag && res.data.flag != "false") {
        wx.requestPayment({
          'timeStamp': res.data.timeStamp,
          'nonceStr': res.data.nonceStr,
          'package': res.data.package,
          'signType': res.data.signType,
          'paySign': res.data.paySign,
          'success': function (res) {
            console.log(res)
            getTuanId(that);
          },
          'fail': function (res) {
            console.log(res)
          }
        })
      } else {
        feedbackApi.showToast({ title: res.data.message, mask: false })//调用 showToast
      }
      that.setData({loading: false, disabled: false})
    }, ...params)
	},
  

  
  /**
   * 页面上拉触底事件的处理函数
   */
	onReachBottom: function () {

	}
})